package com.example.sunmiv1.adapter;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.FragmentManager;

import com.example.sunmiv1.R;
import com.example.sunmiv1.dialog.DeleteGoodDialog;
import com.example.sunmiv1.entity.AllocationGoodsInfo;
import com.example.sunmiv1.entity.DepositGoodsInfo;
import com.example.sunmiv1.entity.GoodsStoreRetreatInfo;
import com.example.sunmiv1.entity.LossGoodsInfo;
import com.example.sunmiv1.entity.ReportLossGoodBean;
import org.application.ClientApplication;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.TextCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ScanGoodAdapter<T> extends BaseAdapter {

    private List<T> list;
    private int type;
    private ViewHolder viewHolder;
    private FragmentManager fragmentManager;
    private ACache aCache;

    public ScanGoodAdapter(FragmentManager manager, List<T> list, int type) {
        fragmentManager = manager;
        this.list = list;
        this.type = type;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        aCache = ACache.get(parent.getContext());
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_scan_good, null);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        final LinearLayout add = viewHolder.scanGoodAdd;
        final LinearLayout reduce = viewHolder.scanGoodReduce;
        final int index = position;
        final EditText editText = viewHolder.scanGoodNum;
        viewHolder.scanGoodItem.setOnLongClickListener(v -> {
            DeleteGoodDialog.newInstance()
                    .startShow(fragmentManager, "")
                    .callback(o -> {
                        list.remove(index);
                        notifyDataSetChanged();
                    })
                    .setCancelable(false);
            return true;
        });
        switch (type) {//報損/盤點/採購/採購退貨/出庫    1/2/3/4/5
            case 1:
                List<LossGoodsInfo.DataBean> s = (List<LossGoodsInfo.DataBean>) list;
                setText(s.get(position).getGoods_name(), s.get(position).getSku_name(), s.get(position).getLoss_num());
                if ("1".equals(s.get(position).getSerial_number_state())) {
                    editText.setEnabled(false);
                } else {
                    editText.setEnabled(true);
                }
                editText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable editable) {
                        s.get(index).setLoss_num(editText.getText().toString().trim());
                    }
                });
                add.setOnClickListener(v -> {
                    if ("1".equals(s.get(index).getSerial_number_state())) {
                        Toast.makeText(parent.getContext(), "串碼商品不能更改數量", Toast.LENGTH_SHORT).show();
                    } else {
                        if (TextUtils.isEmpty(s.get(index).getLoss_num())) {
                            s.get(index).setLoss_num("1");
                        } else {
                            s.get(index).setLoss_num((Integer.parseInt(s.get(index).getLoss_num()) + 1) + "");
                        }
                        notifyDataSetChanged();
                    }
                });
                reduce.setOnClickListener(v -> {
                    if ("1".equals(s.get(index).getSerial_number_state())) {
                        Toast.makeText(parent.getContext(), "串碼商品不能更改數量", Toast.LENGTH_SHORT).show();
                    } else {
                        if (!TextUtils.isEmpty(s.get(index).getLoss_num()) && Integer.parseInt(s.get(index).getLoss_num()) > 1) {
                            s.get(index).setLoss_num((Integer.parseInt(s.get(index).getLoss_num()) - 1) + "");
                        } else {
                            DeleteGoodDialog.newInstance()
                                    .startShow(fragmentManager, "")
                                    .callback(o -> {
                                        list.remove(index);
                                        notifyDataSetChanged();
                                    })
                                    .setCancelable(false);
                        }
                        notifyDataSetChanged();
                    }
                });
                break;
            case 2:
                List<ReportLossGoodBean.DataBean.ListBean> r = (List<ReportLossGoodBean.DataBean.ListBean>) list;
                setText(r.get(position).getGoods_name(), r.get(position).getSku_name(), r.get(position).getInventory_num());
                if ("1".equals(r.get(position).getSerial_number_state())) {
                    editText.setEnabled(false);
                } else {
                    editText.setEnabled(true);
                }
                editText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable editable) {
                        r.get(index).setInventory_num(editText.getText().toString().trim());
                    }
                });
                add.setOnClickListener(v -> {
                    if ("1".equals(r.get(index).getSerial_number_state())) {
                        Toast.makeText(parent.getContext(), "串碼商品不能更改數量", Toast.LENGTH_SHORT).show();
                    } else {
                        if (TextUtils.isEmpty(r.get(index).getInventory_num())) {
                            r.get(index).setInventory_num("1");
                        } else {
                            r.get(index).setInventory_num(((int) Double.parseDouble(r.get(index).getInventory_num()) + 1) + "");
                        }
                        notifyDataSetChanged();
                    }
                });
                reduce.setOnClickListener(v -> {
                    if ("1".equals(r.get(index).getSerial_number_state())) {
                        Toast.makeText(parent.getContext(), "串碼商品不能更改數量", Toast.LENGTH_SHORT).show();
                    } else {
                        if (!TextUtils.isEmpty(r.get(index).getInventory_num()) && (int) Double.parseDouble(r.get(index).getInventory_num()) > 1) {
                            r.get(index).setInventory_num(((int) Double.parseDouble(r.get(index).getInventory_num()) - 1) + "");
                        } else {
                            DeleteGoodDialog.newInstance()
                                    .startShow(fragmentManager, "")
                                    .callback(o -> {
                                        if (aCache.getAsString("order_id") != null && !TextUtils.isEmpty(aCache.getAsString("order_id"))) {
                                            deleteGood(index);
                                        } else {
                                            list.remove(index);
                                            notifyDataSetChanged();
                                        }
                                    })
                                    .setCancelable(false);
                        }
                        notifyDataSetChanged();
                    }
                });
                break;
            case 3:
                List<DepositGoodsInfo.DataBean.ListBean> d = (List<DepositGoodsInfo.DataBean.ListBean>) list;
                setText(d.get(position).getGoods_name(), d.get(position).getSku_name(), d.get(position).getPurchase_num());
                if ("1".equals(d.get(position).getSerial_number_state())) {
                    editText.setEnabled(false);
                } else {
                    editText.setEnabled(true);
                }
                editText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable editable) {
                        d.get(index).setPurchase_num(editText.getText().toString().trim());
                    }
                });
                add.setOnClickListener(v -> {
                    if ("1".equals(d.get(index).getSerial_number_state())) {
                        Toast.makeText(parent.getContext(), "串碼商品不能更改數量", Toast.LENGTH_SHORT).show();
                    } else {
                        if (TextUtils.isEmpty(d.get(index).getPurchase_num())) {
                            d.get(index).setPurchase_num("1");
                        } else {
                            d.get(index).setPurchase_num((Integer.parseInt(d.get(index).getPurchase_num()) + 1) + "");
                        }
                        notifyDataSetChanged();
                    }
                });
                reduce.setOnClickListener(v -> {
                    if ("1".equals(d.get(index).getSerial_number_state())) {
                        Toast.makeText(parent.getContext(), "串碼商品不能更改數量", Toast.LENGTH_SHORT).show();
                    } else {
                        if (!TextUtils.isEmpty(d.get(index).getPurchase_num()) && Integer.parseInt(d.get(index).getPurchase_num()) > 1) {
                            d.get(index).setPurchase_num((Integer.parseInt(d.get(index).getPurchase_num()) - 1) + "");
                        } else {
                            DeleteGoodDialog.newInstance()
                                    .startShow(fragmentManager, "")
                                    .callback(o -> {
                                        list.remove(index);
                                        notifyDataSetChanged();
                                    })
                                    .setCancelable(false);
                        }
                        notifyDataSetChanged();
                    }
                });
                break;
            case 4:
                List<GoodsStoreRetreatInfo.DataBean> sr = (List<GoodsStoreRetreatInfo.DataBean>) list;
                setText(sr.get(position).getGoods_name(), sr.get(position).getSku_name(), sr.get(position).getRetreat_num_act() + "");
                if ("1".equals(sr.get(position).getSerial_number_state())) {
                    editText.setEnabled(false);
                } else {
                    editText.setEnabled(true);
                }
                editText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable editable) {
                        if (!TextUtils.isEmpty(editText.getText().toString().trim())) {
                            sr.get(index).setRetreat_num_act(Double.parseDouble(editText.getText().toString().trim()));
                        } else {
                            sr.get(index).setRetreat_num_act((double) 1);
                            notifyDataSetChanged();
                        }
                    }
                });
                add.setOnClickListener(v -> {
                    if ("1".equals(sr.get(index).getSerial_number_state())) {
                        Toast.makeText(parent.getContext(), "串碼商品不能更改數量", Toast.LENGTH_SHORT).show();
                    } else {
                        if (sr.get(index).getRetreat_num_act() == null) {
                            sr.get(index).setRetreat_num_act((double) 1);
                        } else {
                            sr.get(index).setRetreat_num_act(Double.parseDouble((sr.get(index).getRetreat_num_act() + 1) + ""));
                        }
                        notifyDataSetChanged();
                    }
                });
                reduce.setOnClickListener(v -> {
                    if ("1".equals(sr.get(index).getSerial_number_state())) {
                        Toast.makeText(parent.getContext(), "串碼商品不能更改數量", Toast.LENGTH_SHORT).show();
                    } else {
                        if (sr.get(index).getRetreat_num_act() != null && sr.get(index).getRetreat_num_act() > 1) {
                            sr.get(index).setRetreat_num_act(Double.parseDouble(((sr.get(index).getRetreat_num_act()) - 1) + ""));
                        } else {
                            DeleteGoodDialog.newInstance()
                                    .startShow(fragmentManager, "")
                                    .callback(o -> {
                                        list.remove(index);
                                        notifyDataSetChanged();
                                    })
                                    .setCancelable(false);
                        }
                        notifyDataSetChanged();
                    }
                });
                break;
            case 5:
                List<AllocationGoodsInfo.DataBean> ag = (List<AllocationGoodsInfo.DataBean>) list;
                setText(ag.get(position).getGoods_name(), ag.get(position).getSku_name(), ag.get(position).getOutput_num());
                if ("1".equals(ag.get(position).getSerial_number_state())) {
                    editText.setEnabled(false);
                } else {
                    editText.setEnabled(true);
                }
                editText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable editable) {
                        ag.get(index).setOutput_num(editText.getText().toString().trim());
                    }
                });
                add.setOnClickListener(v -> {
                    if ("1".equals(ag.get(index).getSerial_number_state())) {
                        Toast.makeText(parent.getContext(), "串碼商品不能更改數量", Toast.LENGTH_SHORT).show();
                    } else {
                        if (TextUtils.isEmpty(ag.get(index).getOutput_num())) {
                            ag.get(index).setOutput_num("1");
                        } else {
                            ag.get(index).setOutput_num((Integer.parseInt(ag.get(index).getOutput_num()) + 1) + "");
                        }
                        notifyDataSetChanged();
                    }
                });
                reduce.setOnClickListener(v -> {
                    if ("1".equals(ag.get(index).getSerial_number_state())) {
                        Toast.makeText(parent.getContext(), "串碼商品不能更改數量", Toast.LENGTH_SHORT).show();
                    } else {
                        if (!TextUtils.isEmpty(ag.get(index).getOutput_num()) && Integer.parseInt(ag.get(index).getOutput_num()) > 1) {
                            ag.get(index).setOutput_num((Integer.parseInt(ag.get(index).getOutput_num()) - 1) + "");
                        } else {
                            DeleteGoodDialog.newInstance()
                                    .startShow(fragmentManager, "")
                                    .callback(o -> {
                                        list.remove(index);
                                        notifyDataSetChanged();
                                    })
                                    .setCancelable(false);
                        }
                        notifyDataSetChanged();
                    }
                });
                break;
            default:
                break;
        }
        return convertView;
    }

    private void setText(String goods_name, String sku_name, String loss_num) {
        viewHolder.scanGoodName.setText(goods_name);
        viewHolder.scanGoodSku.setText(sku_name);
        viewHolder.scanGoodNum.setText(loss_num);
    }

    private void deleteGood(int index) {
        List<ReportLossGoodBean.DataBean.ListBean> r = (List<ReportLossGoodBean.DataBean.ListBean>) list;
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("order_id", aCache.getAsString("order_id"));
            jsonObject.put("inventory_goods_id", r.get(index).getId());
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(ClientApplication.context, Common.DELETE_GOODS_RECORD, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        JSONObject json = new JSONObject(text);
                        if (json.getInt("status") == 1) {
                            list.remove(index);
                            notifyDataSetChanged();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    static class ViewHolder {
        @BindView(R.id.scanGood_name)
        TextView scanGoodName;
        @BindView(R.id.scanGood_sku)
        TextView scanGoodSku;
        @BindView(R.id.scanGood_reduce)
        LinearLayout scanGoodReduce;
        @BindView(R.id.scanGood_num)
        EditText scanGoodNum;
        @BindView(R.id.scanGood_add)
        LinearLayout scanGoodAdd;
        @BindView(R.id.scanGood_item)
        LinearLayout scanGoodItem;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
